package com.wzp.puppet;


import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;

public class HomeActivity extends Activity {

    ScrollView scrollView;
    TextView tvMessage;
    Main main;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_home);

        findViewById(R.id.start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    new Thread(){
                        @Override
                        public void run() {
                            super.run();
                            try {
                                if (main == null) {
                                    main = new Main(HomeActivity.this);
                                    main.setLogListener(new Main.LogListener() {
                                        @Override
                                        public void printLog(String log) {
                                            printMessage(log);
                                        }
                                    });
                                }
                                main.start();
                            } catch (Exception e) {
                                e.printStackTrace();
                                printMessage(e.getMessage());
                            }
                        }
                    }.start();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (main != null) {
                    main.stop();
                }
            }
        });

        scrollView = (ScrollView) findViewById(R.id.scrollView);
        tvMessage = (TextView) findViewById(R.id.message);
    }

    StringBuilder builder = new StringBuilder();
    public void printMessage(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                builder.append(msg + "\n");
                tvMessage.setText(builder.toString());

                if (builder.length() > 1000) {
                    builder.delete(0, 500);
                }

                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                });
            }
        });

    }
}
